package ControllerLayer;

import java.security.MessageDigest;
import java.sql.SQLException;
import java.util.ArrayList;

import DBLayer.*;
import ModelLayer.*;


/**
 * 
 * @author DMAA0213 - Gruppe 2
 *
 */
public class MedlemsController implements IFMedlemsController {
	
	private IFDBMedlem medlemmer;
	
	public MedlemsController() throws SQLException {
		try {
			medlemmer = new DBMedlem();
		}
		catch (SQLException e) {
			throw e;
		}
	}

	@Override
	public Medlem loginMedlem(String email, String password) throws SQLException {
		// TODO Auto-generated method stub
		try {
			return medlemmer.login(email.toLowerCase(), beregnSHA1(password));
		} catch (SQLException e) {
			throw e;
		}
	}

	private String beregnSHA1(String input) {
		try {
			MessageDigest m = MessageDigest.getInstance("SHA1");
			m.update(input.getBytes("UTF-8"));
			byte[] res = m.digest();
			String result = "";
			int index = 0;
			while(index < res.length) {
				result += byteToHex(res[index]);
				index++;
			}
			return result;
		}
		catch (Exception e) {
			return e.getMessage();
		}		
	}
	
	private String byteToHex(byte input) {
		String result = Integer.toHexString(input & 0xFF);
		while (result.length() < 2) {
			result = "0" + result;
		}
		return result;
	}

	@Override
	public ArrayList<Medlem> hentMedlemsListe() throws SQLException {
		return medlemmer.hentListe();
	}
	

}
